package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import common.ServerResponse;
import entity.Banji;
import entity.PageBean;
import entity.Province;
import entity.Student;
import entity.User;
import util.JDBCUtil;
import util.JSONUtil;
import net.sf.json.JSONArray;
import service.IStudentService;
import service.impl.StudentServiceImpl;

@WebServlet("/student")
public class StudentServlet extends HttpServlet	{
	
	private IStudentService studentService = new StudentServiceImpl();
	
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//		req.setCharacterEncoding("utf-8");
		String method = req.getParameter("method");
		if (null == method || "".equals(method)) {
			method = "pageList";
		}
		switch (method) {
		case "getRegisterPage":
			getRegisterPage(req, resp);
			break;
		case "getInsertPage":
			getInsertPage(req, resp);
			break;
		case "deleteById":
			deleteById(req, resp);
			break;
		case "selectAll":
			selectAll(req, resp);
			break;
		case "toUpdate":
			toUpdate(req, resp);
			break;
		case "insert":
			insert(req, resp);
			break;
		case "search":
			search(req, resp);
			break;
		case "update":
			update(req, resp);
			break;
		case "pageList":
			pageList(req, resp);
			break;
		case "checkName":
			checkName(req, resp);
			break;
		case "selectClass":
			selectClass(req, resp);
			break;
		case "selectStudentBanjiInfo":
			selectStudentBanjiInfo(req, resp);
			break;
		default:
			System.out.println("default");
			break;
		}
	}
	private void getRegisterPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		req.getRequestDispatcher("/register.jsp").forward(req, resp);
	}
	private void selectStudentBanjiInfo(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<Map<String, Object>> list= studentService.selectStudentBanjiInfo();
		req.setAttribute("list", list);
		req.getRequestDispatcher("/student_banji_list.jsp").forward(req, resp);
	}
	private void getInsertPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<Banji> list = new ArrayList<Banji>();
		Banji banji1 = new Banji(1, "Java开发");
		Banji banji2 = new Banji(2, "UI设计");
		Banji banji3 = new Banji(3, "软件工程");
		list.add(banji1);
		list.add(banji2);
		list.add(banji3);
		
		req.setAttribute("list", list);
		req.getRequestDispatcher("/student_insert.jsp").forward(req, resp);
	}
	private void selectClass(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		ArrayList<Banji> list = new ArrayList<Banji>();
		Connection connection = null;
		Statement statement = null;
		ResultSet resultSet = null;
		try {
			connection = JDBCUtil.getConnection();
			String sql = "SELECT id,name FROM class";
			statement = connection.createStatement();
			resultSet = statement.executeQuery(sql);
			while (resultSet.next()) {
				int id = resultSet.getInt("id");
				String className = resultSet.getString("name");
				Banji banji = new Banji(id,className);
				list.add(banji);
			}

			for (Banji banji : list) {
				System.out.println(banji);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			JDBCUtil.close(connection, statement, resultSet);
		}

		// 以json格式返回List<Province>
		JSONArray jsonArray = JSONArray.fromObject(list);
		resp.setContentType("text/html;charset=utf-8");
		resp.getWriter().write(jsonArray.toString());
	
	}
	private void checkName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String name = req.getParameter("name");
		boolean isExist = studentService.checkName(name);
		
		resp.setContentType("text/html;charset=utf-8");
		// {"isExist":isExist}
		resp.getWriter().write("{\"isExist\":" + isExist + "}");
	}
	private void pageList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String pageNo = req.getParameter("pageNo");
		String pageSize = req.getParameter("pageSize");
		if (null == pageNo || "".equals(pageNo)) {
			pageNo = "1";
		}
		if (null == pageSize || "".equals(pageSize)) {
			pageSize = "10";
		}

		PageBean pageBean = studentService.pageList(Integer.parseInt(pageNo), Integer.parseInt(pageSize));
		
		req.setAttribute("pageBean", pageBean);
		//转发，不需要写路径名，在服务器内部完成
		req.getRequestDispatcher("student_page_list.jsp").forward(req, resp);
	}
	private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String id = req.getParameter("student_id");
		String name = req.getParameter("student_name");
		String age = req.getParameter("student_age");
		String gender = req.getParameter("gender");
		String class_id = req.getParameter("class_id");
		Student student = new Student(Integer.parseInt(id),name,Integer.parseInt(age),gender,Integer.parseInt(class_id));
		boolean isSuccess = studentService.update(student);
		
		req.setAttribute("student", student);
		// 请求转发到student_list.jsp页面进行展示	重定向
		resp.sendRedirect(req.getContextPath() + "/student?method=pageList");
	}

	private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String updateId = req.getParameter("student_id");
		Student student = studentService.selectById(Integer.parseInt(updateId));
		
		// 放到一块内存区域里面
		req.setAttribute("student", student);
		// 请求转发到student_update.jsp页面进行展示
		req.getRequestDispatcher("/student_update.jsp").forward(req, resp);		

	}

	private void search(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		String searchName = req.getParameter("searchName");
		List<Student> list = studentService.search(searchName);
		req.setAttribute("list", list);
		req.getRequestDispatcher("/Student.jsp").forward(req, resp);
	}

	private void insert(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String name = req.getParameter("student_name");
		String age = req.getParameter("student_age");
		String gender = req.getParameter("gender");
		String class_id = req.getParameter("class_id");
		Student student = new Student(name,Integer.parseInt(age),gender,Integer.parseInt(class_id));
		boolean isSuccess = studentService.insert(student);
//		resp.sendRedirect(req.getContextPath() + "/student?method=pageList");
		ServerResponse serverResponse = null;
		if (isSuccess) {
			serverResponse = ServerResponse.createSuccess("添加成功");
		}else {
			serverResponse = ServerResponse.createError("添加失败");
		}
	}

	private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String id = req.getParameter("id");
		boolean isSuccess = studentService.deleteById(Integer.parseInt(id));
		// 删除完了之后重定向到列表界面再展示所有数据
//		resp.sendRedirect(req.getContextPath() + "/student?method=pageList");
		ServerResponse serverResponse = null;
		if (isSuccess) {
			serverResponse = ServerResponse.createSuccess("删除成功");
		}else {
			serverResponse = ServerResponse.createError("删除失败");
		}
		JSONUtil.obj2Json(resp, serverResponse);
	}

	private void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		List<Student>  list = studentService.selectAll();
		
		// 放到一块内存区域里面
		req.setAttribute("list", list);
		// 请求转发到banji_list.jsp页面进行展示
		req.getRequestDispatcher("/Student.jsp").forward(req, resp);
	}

}
